//
//  SLNearByVC.m
//  SlockApp
//
//  Created by 凯朱 on 2024/7/30.
//

#import "SLNearByVC.h"
#import "SLNearBySearchVC.h"
#import <MapKit/MapKit.h>
#import "SLAnnotation.h"
@interface SLNearByVC ()<CLLocationManagerDelegate,MKMapViewDelegate>{
    NSInteger _curRange;
    CLLocation *_regionLocation;//监听的地址
    NSString *_regionAddress;
}
@property (nonatomic,strong) MKMapView *mapView;
@property (nonatomic,strong) CLLocationManager *locaManager;
@property (nonatomic, strong)SLAnnotation *annotion;
@property (nonatomic, strong)id lastCircle;
@property (nonatomic, strong)NSDictionary *settingInfo;
@property (nonatomic, assign)MKCoordinateSpan scale;
@property (nonatomic, strong)UIView *calloutView;
@end

@implementation SLNearByVC

-(void)viewDidLoad{
    [super viewDidLoad];
    _scale = MKCoordinateSpanMake(0.01, 0.01);
    [self initRegionData];
    [self setUpSubViews];
    [self getDeviceData];
}

//监听的数据
-(void)initRegionData{
    if (kCurClickDevice.regionDistance == 0) {
        _curRange = 100;
    }else{
        _curRange = kCurClickDevice.regionDistance;
    }
    if (kCurClickDevice.dbLatitude.length > 0 && kCurClickDevice.dbLongitude.length > 0) {
        _regionLocation = [[CLLocation alloc] initWithLatitude:[kCurClickDevice.dbLatitude doubleValue] longitude:[kCurClickDevice.dbLongitude doubleValue]];
        _regionAddress = kCurClickDevice.regionAddress;
    }
}

//获取硬件数据
-(void)getDeviceData{
    [ZCTool showLoadingOnKeyWindow];
    [ZCTool connectDeviceWith:kCurClickDevice toast:kLocalString(@"Connecting...") finish:^(BOOL isSuccess) {
        [ZCTool hideLoadingOnKeyWindow];
        if (!isSuccess) {
            [self refresSubViews];
            return;
        }
        //获取硬件数据
        [self getDeviceSettingData:NO];
    }];
}

-(void)getDeviceSettingData:(BOOL)needUpload{
    //设置数据
    kWeakSelf(self);
    [[SLBluetoothManager sharedManager] getDeviceSettingInfo:^(id data) {
        weakself.settingInfo = data;
        kCurClickDevice.isOpenDbModel = [self.settingInfo[@"isOpenDbModel"] boolValue];
        //上报开关信息
        if (needUpload) {
            [ZKHttpManager sysncDeviceDataWith:@{@"isOpenDbModel":self.settingInfo[@"isOpenDbModel"]} finished:nil];
        }
        [self refresSubViews];
    }];
}

//上报地点信息
-(void)uploadDbModelLocationData{
    NSDictionary *params = @{@"regionDistance":kSTRING(@(_curRange)),
                             @"dbLongitude":kSTRING(@(_regionLocation.coordinate.longitude)),
                             @"dbLatitude":kSTRING(@(_regionLocation.coordinate.latitude)),
                             @"regionAddress":_regionAddress};
    [ZKHttpManager sysncDeviceDataWith:params finished:nil];
}

- (IBAction)changeAction:(UISwitch *)sender {
    if (kCurClickDevice.isOpenEnergyModel) {
        NSString *title = kLocalString(@"Switch off 'Energy saving mode' first.");
        NSString *msg = kLocalString(@"By searching bluetooth for identity pre-recognition, speeds up fingerprint unlocking when your fingers are wet or dirty. Enabling this feature may increase power consumption.");
        [SLTipAlertView showWith:title content1:msg content2:@"" doneBtn:kLocalString(@"OK") cancelBtn:@"" action:^(NSInteger index) {
            
        }];
        sender.on = NO;
        return;
    }
    [ZCTool showLoadingOnKeyWindow];
    kWeakSelf(self);
    //连接上
    [[SLBluetoothManager sharedManager] setDbModel:_changeBtn.isOn finish:^(NSString *commond, BOOL isSuccess, id data, NSString *errorMsg) {
        [ZCTool hideLoadingOnKeyWindow];
        if (!isSuccess) {
            [self refresSubViews];
            kShowToast(@"Set faild");
            return;
        }
        //设置成功，刷新
        [weakself getDeviceSettingData:YES];
    }];
}

-(void)refresSubViews{
    NSString *value = _settingInfo ? _settingInfo[@"isOpenDbModel"] : kSTRING(@(kCurClickDevice.isOpenDbModel));
     _changeBtn.on = [value boolValue];
}

-(void)setUpSubViews{
    self.title = kLocalString(@"Set hot area");
    _topLbl1.text = kLocalString(@"Set hot area");
    _topContentLbl.text = kLocalString(@"By searching Bluetooth for identity pre-recognition, speeds up fingerprint unlocking when your fingers are wet or dirty, saving energy for your padlock to matain longer battery life as well.");
    _tipLbl1.text = kLocalString(@"Padlock hot area");
    _mapBgView.layer.cornerRadius = 20;
    _mapBgView.layer.masksToBounds = YES;
    _topView.layer.cornerRadius = 20;
    _topView.layer.masksToBounds = YES;
    kWeakSelf(self);
    _mapBgView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [weakself pushToSearchVc];
    }];
    [_mapBgView addGestureRecognizer:tap];
    
    [self addMapView];
    [self startLocation];
    _topView.hidden = YES;
    _topViewHeight.constant = 0;
}

-(void)addMapView{
    //创建MKMapView，设置控件视图大小
    MKMapView *mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, _mapBgView.width, _mapBgView.height)];
    //设置地图类型
    mapView.mapType = MKMapTypeStandard;
    mapView.userInteractionEnabled = NO;
    //设置代理
    mapView.delegate = self;
    [self.mapBgView addSubview:mapView];
    self.mapView = mapView;
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    //停止获取位置信息
    [self.locaManager stopUpdatingLocation];
    //获取位置对象
    if (!_regionLocation) {
        _regionLocation = [locations lastObject];
        [self uploadDbModelLocationData];
    }
    [self addAnnotationsToMapView:_regionLocation];
    MKCoordinateRegion region = MKCoordinateRegionMake(_regionLocation.coordinate, _scale);
    [self.mapView setRegion:region animated:YES];
}

-(void)addAnnotationsToMapView:(CLLocation *)location{
    CLLocationCoordinate2D location1 = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);
    //创建大头针
    SLAnnotation *annotation = [[SLAnnotation alloc] init];
    annotation.coordinate = location1;
    annotation.icon = [UIImage imageNamed:@"icon_location"];
    _annotion = annotation;
    //添加大头针
    [self.mapView addAnnotation:annotation];
    [self drawCircleAroundAnnotation];
}

//更新region的位置
-(void)updateLoactionCenter:(CLLocationCoordinate2D)coordinate{
    // 更新标注的位置
    _annotion.coordinate = coordinate;
    [self.mapView removeAnnotation:_annotion];
    [self.mapView addAnnotation:_annotion];
    
    //更新圆形区域的位置
    [self drawCircleAroundAnnotation];
    //更新地图中心位置
    MKCoordinateRegion region = MKCoordinateRegionMake(coordinate, _scale);
    [self.mapView setRegion:region animated:YES];
}

-(void)drawCircleAroundAnnotation{
    if (_lastCircle) {
        [self.mapView removeOverlay:_lastCircle];
    }
    CLLocationDistance radius = _curRange;
    MKCircle *circle = [MKCircle circleWithCenterCoordinate:_annotion.coordinate radius:radius];
    [self.mapView addOverlay:circle]; // 添加圆形覆盖层
    _lastCircle = circle;
}

// 实现 MKMapViewDelegate 方法以渲染圆形
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay {
    if ([overlay isKindOfClass:[MKCircle class]]) {
        MKCircleRenderer *circleRenderer = [[MKCircleRenderer alloc] initWithCircle:(MKCircle *)overlay];
        circleRenderer.fillColor = [KColor_O colorWithAlphaComponent:0.3]; // 填充颜色
        circleRenderer.strokeColor = KColor_O; // 边框颜色
        circleRenderer.lineWidth = 3; // 边框宽度
        return circleRenderer;
    }
    return nil;
}

-(void)startLocation{
    //初始化LocationManager
    self.locaManager = [[CLLocationManager alloc] init];
    [self.locaManager requestAlwaysAuthorization];
    //设置代理
    [_locaManager setDelegate:self];
    //设置位置的精度
    [_locaManager setDesiredAccuracy:kCLLocationAccuracyBest];
    //是指多远才更新位置信息
    [_locaManager setDistanceFilter:5.0f];
    //开始定位
    [_locaManager startUpdatingLocation];
}

//自定义大头针view
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    //假如是定位的蓝色大头针，直接返回nil
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        return nil;
    }
    
    //可重用ID
    static NSString *viewID = @"myAnnotation";
    //从缓存池中取
    MKAnnotationView *annoView = [mapView dequeueReusableAnnotationViewWithIdentifier:viewID];
    //加入没有重新创建
    if(annoView == nil){
        annoView = [[MKAnnotationView alloc] init];
    }
    //赋值
    annoView.image = [UIImage imageNamed:@"icon_location"];
    
//    // 允许显示气泡
//    annoView.canShowCallout = NO;
//    if (_regionAddress.length > 0) {
//       CGSize size = STRING_SIZE_FONT(1000, _regionAddress, kFont(13));
//        CGFloat width = size.width+20;
//        // 创建气泡视图
//        UIView *calloutView = [[UIView alloc] initWithFrame:CGRectMake(annoView.center.x - width/2, annoView.center.y - 40, width, 25)];
//        calloutView.backgroundColor = KColor_1;
//        calloutView.layer.cornerRadius = 5;
//        // 添加标题标签
//        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 25)];
//        titleLabel.text = _regionAddress; // 替换为实际地址
//        titleLabel.textColor = KWhiteColor_text;
//        titleLabel.font = kFont(13);
//        titleLabel.textAlignment = NSTextAlignmentCenter;
//        [calloutView addSubview:titleLabel];
//        calloutView.tag = 101;
//        // 将气泡视图添加到大头针上
//        [annoView addSubview:calloutView];
//        self.calloutView = calloutView;
//    }else{
//        UIView *calloutView = [annoView viewWithTag:101];
//        if (calloutView) {
//            [calloutView removeFromSuperview];
//        }
//    }
    return annoView;
}

-(void)pushToSearchVc{
    SLNearBySearchVC *vc = [[SLNearBySearchVC alloc] init];
    vc.regionLocation = _regionLocation;
    vc.curRange = _curRange;
    vc.scale = _scale;
    [vc setUpdateRegionBlock:^(CLLocation * _Nonnull location, NSString * _Nonnull address, NSInteger range) {
        self->_regionLocation = location;
        self->_regionAddress = address;
        self->_curRange = range;
        [self updateLoactionCenter:location.coordinate];
    }];
    [self.navigationController pushViewController:vc animated:YES];
}






@end
